package com.gopay.checkorder.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.AbcConstants;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.abc.ebank.AbcB2cMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * @CheckOrderAbcB2cImpl.java
 * @author LiLiLi
 */
public class CheckOrderAbcB2cImpl implements BankOrderService {

	private final static Logger logger = LoggerFactory.getLogger("ABC");

	@Resource(name = "bankClient")
	private BankInteractRemoteService bankClient;

	@Override
	public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {

		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
		checkOrderResult.setOrderId(bankOrder.getOrderId());

		AbcB2cMessage base = new AbcB2cMessage();
		base.setOrderId(bankOrder.getOrderId());
		base.setBankOrderId(bankOrder.getOutOrderId());
		base.setBank(BankConstants.BANK_LOGO_ABC);
		base.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
		base.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));

		Result result = new Result();
		try {
			result = bankClient.query(base);

			if (result == null || !result.isSuccess() || result.getDefaultModel() == null) {
				logger.error(bankOrder.getOrderId() + " bankClient fail.");
				if (result == null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())) {
					BankCountDownLatch.failIncrease(bankOrder.getBankCode());
					checkOrderResult.setCommunicateError(true);
				}
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("系统返回对账结果为空");
				return checkOrderResult;
			}

			AbcB2cMessage res = (AbcB2cMessage) result.getDefaultModel();
			if (res == null) {
				// 查询订单为空
				logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + ProcCodeConstants.PROC_CODE_100E6022 + " err:bis query is null.");
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("银行返回对账结果为空");
				return checkOrderResult;
			}

			if (StringUtils.isEmpty(res.getOrderStatus())) {
				// 查询订单错误
				logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + res.getReturnCode() + " err:" + res.getErrorMessage());
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
				checkOrderResult.setErrMsg(res.getErrorMessage());
				return checkOrderResult;
			}

			if (res.getOrderStatus() != null && !res.getOrderStatus().equals("")) {
				// 订单已请款(订单已支付) 03状态银行已不用
//				if (AbcConstants.ABC_B2C_ORDERSTATUS_PAYMENT_ORDERS.equals(res.getOrderStatus())) {
//					checkOrderResult.setSuccess(true);
//					InAccInfo accInfo = new InAccInfo();
//					accInfo.setOrderId(bankOrder.getOrderId());
//					accInfo.setAmount(new BigDecimal(res.getResAmount()));
//					accInfo.setRetCode("00");
//					accInfo.setCardType(BankCardType.Unknown.toString());
//					checkOrderResult.setAccInfo(accInfo);
//					logger.error("农业银行B2C订单:" + bankOrder.getOutOrderId() + ",交易成功返回信息：" + AbcConstants.ABC_B2C_PAYMENT_ORDERS_MESSAGE + ",查到的订单状态:" + res.getOrderStatus());
//				}
				// 订单状态成功(订单已结算)
				if (AbcConstants.ABC_ORDERSTATUS_SETTLEMENT_ORDER.equals(res.getOrderStatus())) {
					checkOrderResult.setSuccess(true);
					InAccInfo accInfo = new InAccInfo();
					accInfo.setOrderId(bankOrder.getOrderId());
					accInfo.setAmount(new BigDecimal(res.getResAmount()));
					accInfo.setRetCode("00");
					accInfo.setCardType(BankCardType.Unknown.toString());
					checkOrderResult.setAccInfo(accInfo);
					logger.error("农业银行B2C订单:" + bankOrder.getOutOrderId() + ",交易成功返回信息：" + AbcConstants.ABC_SETTLEMENT_ORDER_MESSAGE + ",查到的订单状态:" + res.getOrderStatus());
				}
				// 订单状态暂不处理(订单已建立，等待支付)
				else if (AbcConstants.ABC_ORDERSTATUS_ESTABLISH.equals(res.getOrderStatus())) {
					logger.error("农业银行B2C订单:" + bankOrder.getOutOrderId() + ",交易返回信息：" + AbcConstants.ABC_ESTABLISH_MESSAGE + ",暂不进行账务处理,查到的订单状态:" + res.getOrderStatus());
					checkOrderResult.setErrMsg(AbcConstants.ABC_ESTABLISH_MESSAGE);
				}
				// 订单状态暂不处理(订单无回应)
				else if (AbcConstants.ABC_ORDERSTATUS_CONSUMER_PAID.equals(res.getOrderStatus())) {
					logger.error("农业银行B2C订单:" + bankOrder.getOutOrderId() + ",交易返回信息：" + AbcConstants.ABC_CONSUMER_PAID_MESSAGE + ",暂不进行账务处理,查到的订单状态:" + res.getOrderStatus());
					checkOrderResult.setErrMsg(AbcConstants.ABC_CONSUMER_PAID_MESSAGE);
				}
				// 订单状态暂不处理(订单已退款)
				else if (AbcConstants.ABC_ORDERSTATUS_REFUND.equals(res.getOrderStatus())) {
					logger.error("农业银行B2C订单:" + bankOrder.getOutOrderId() + ",交易返回信息：" + AbcConstants.ABC_REFUND_MESSAGE + ",暂不进行账务处理,查到的订单状态:" + res.getOrderStatus());
					checkOrderResult.setErrMsg(AbcConstants.ABC_REFUND_MESSAGE);
				}
				// 订单状态失败处理(订单已取消)
				else if (AbcConstants.ABC_ORDERSTATUS_CANCEL.equals(res.getOrderStatus())) {
					// 失败处理
					checkOrderResult.setBankFailure(true);
					logger.error("农业银行B2C订单:" + bankOrder.getOutOrderId() + ",交易返回信息：" + AbcConstants.ABC_CANCEL_MESSAGE + ",暂不进行账务处理,查到的订单状态:" + res.getOrderStatus());
					checkOrderResult.setErrMsg(AbcConstants.ABC_CANCEL_MESSAGE);
				}
				// 订单状态失败处理(订单支付失败）
				else if (AbcConstants.ABC_ORDERSTATUS_FAILURE.equals(res.getOrderStatus())) {
					checkOrderResult.setBankFailure(true);
					logger.error("农业银行B2C订单:" + bankOrder.getOutOrderId() + ",交易返回信息：" + AbcConstants.ABC_FAILURE_MESSAGE + ",暂不进行账务处理,查到的订单状态:" + res.getOrderStatus());
					checkOrderResult.setErrMsg(AbcConstants.ABC_FAILURE_MESSAGE);
				} else {
					logger.error("农业银行B2C订单:" + bankOrder.getOutOrderId() + "交易结果未明确" + " errcode:" + res.getReturnCode() + " err:" + res.getErrorMessage());
					checkOrderResult.setErrMsg("交易结果未明确");
				}

			} else {
				logger.error(" ABC B2C orderId:" + bankOrder.getOrderId() + ",returnMsg:  not found order");
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
				checkOrderResult.setErrMsg("银行返回订单未查到");
			}

			return checkOrderResult;
		} catch (Exception e) {
            logger.error(bankOrder.getOutOrderId() + " bankClient fail.", e);
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("系统对账异常");
			return checkOrderResult;
		}
	}

	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}

}
